package cn.tyoui.analyzerImpl;

import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 扩展工具类
 *
 * @author Tyoui
 * @version 1.8.1
 */
public class Analysis extends AnalysisImpl {
    static Logger log = Logger.getLogger(Analysis.class);

    /**
     * 解析URL中文编码
     *
     * @param urlCode URL字符串
     * @return 解析后的字符串
     */
    public String decode(String urlCode) {
        try {
            return URLDecoder.decode(urlCode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 解析url中的键值对信息
     *
     * @param encode url中的值
     * @return 键值对
     */
    public Map<String, String> keyWord(String encode) {
        Map<String, String> map = new HashMap<>();
        try {
            String string[] = encode.split(" ");
            if (string == null || string.length < 3)
                throw new Exception("解码错误" + encode);
            if (string[1].length() < 4)
                throw new Exception("输入参数有问题。请输入key=values模式");
            String str = string[1];
            String key = str.substring(1, 4);
            String values = str.substring(4);
            map.put(key, values);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return map;
    }

    /**
     * 将数组装换成字符串
     *
     * @param list  数组
     * @param split 分隔符
     * @return 字符串
     */
    public String listToString(List<String> list, String split) {
        String text = "";
        if (list != null) {
            for (String s : list) {
                text += s + split;
            }
            text = text.substring(0, text.length() - 1);
        }
        return text;
    }

    /**
     * 返回Json数据
     *
     * @param str   字符串
     * @param split 分隔符
     * @return Json格式
     */
    public String json(String str, String split) {
        String json = "";
        if (split != null) {
            String[] string = str.split(split);
            for (String s : string) {
                json += "\"" + s + "\",";
            }
            json = "{\"url\":[" + json.substring(0, json.length() - 1) + "]}";
        } else {
            json = "{\"add\":\"" + str + "\"}  ";
        }
        return json;
    }
}

